package com.tian.print.http;

import com.tian.print.BuildConfig;
import com.tian.print.http.interceptor.RequestInterceptor;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 获取Retrofit
 *
 * @author skyTian
 * @desc 获取Retrofit对象的基类
 * @date 2017/9/7 15:49
 */
public class RetrofitClient {

    private static volatile OkHttpClient client;
    private static volatile Retrofit builder;

    /**
     * double-check
     *
     * @return
     */
    public static Retrofit getInstance() {

        //初始化 OKHttp
        if (client == null) {
            synchronized (RetrofitClient.class) {
                if (client == null) {
                    //log日志
                    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    client = new OkHttpClient.Builder()
                            .addInterceptor(new RequestInterceptor())
                            .addInterceptor(loggingInterceptor)
                            .readTimeout(5, TimeUnit.MINUTES)
                            .writeTimeout(5, TimeUnit.MINUTES)
                            .connectTimeout(20, TimeUnit.SECONDS)
                            .build();
                }
            }
        }

        if (builder == null) {
            synchronized (RetrofitClient.class) {
                if (builder == null)
                    builder = new Retrofit.Builder()
                            .baseUrl(BuildConfig.HTTP_ROOT)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .client(client)
                            .build();
            }
        }
        return builder;
    }

}
